package servlet;

import api.APIException;
import model.DBUtil;
import model.User;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.io.PrintWriter;
import java.io.UnsupportedEncodingException;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.sql.*;

@WebServlet("/register")
public class RegisterServlet extends HttpServlet {
    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        //读取用户信息
        req.setCharacterEncoding("utf-8");
        String username = req.getParameter("username");
        String nickname = req.getParameter("nickname");
        String password = req.getParameter("password");
        //数据存储
        PrintWriter out=resp.getWriter();
     if(username.length()==0||password.length()==0){
         out.print("<script language='javascript'>alert('Wrong password. Login again!!');window.location.href='/register.html';</script>");
         return;
     }

        User user ;
        try {
            user = save(username, nickname, password);

        HttpSession session = req.getSession();
        session.setAttribute("currentUser", user);

        //完成登录
        //引导浏览器回到首页
        resp.sendRedirect("/");
    } catch (SQLException throwable) {
            throwable.printStackTrace();
        }
    }

    private User save(String username, String nickname, String password) throws SQLException {
        password = hash(password);
            try (Connection c = DBUtil.getConnection()) {
                String sql = "INSERT INTO user(username,nickname,password) VALUES(?,?,?)";
                try (PreparedStatement s = c.prepareStatement(sql, Statement.RETURN_GENERATED_KEYS)) {
                    s.setString(1, username);
                    s.setString(2, nickname);
                    s.setString(3, password);

                        s.executeUpdate();

                    try (ResultSet rs = s.getGeneratedKeys()) {
                        if (!rs.next()) {
                            return null;
                        }
                        User user = new User();
                        user.username = username;
                        user.nickname = nickname;
                        user.uid = rs.getInt(1);
                        return user;
                    }
                }
            }
        }


    private String hash(String password) {
        try {
            MessageDigest messageDigest = MessageDigest.getInstance("SHA-512");
                byte[] bytes = password.getBytes("UTF-8");
                byte[] digest = messageDigest.digest(bytes);
                StringBuilder sb = new StringBuilder();
                for (byte b : digest) {
                    sb.append(String.format("%02x", b));
                }
                return sb.toString();

        }catch (Exception exc){
            return password;
        }
    }
}
